package com.sillyhat.project.org.menu.service.impl;

import com.sillyhat.project.common.constants.Constants;
import com.sillyhat.project.common.dto.DataTables;
import com.sillyhat.project.org.menu.dto.MenuDTO;
import com.sillyhat.project.org.menu.mapper.MenuMapper;
import com.sillyhat.project.org.menu.service.MenuService;
import com.sillyhat.project.redis.service.RedisService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;

@Service
public class MenuServiceImpl implements MenuService{

	@Resource
	private MenuMapper menuMapper;

	@Autowired
	private RedisService redisService;

	@Override
	public MenuDTO addMenu(MenuDTO dto) {
		menuMapper.insertMenu(dto);
		return dto;
	}

	@Override
	public MenuDTO updateMenu(MenuDTO dto) {
		menuMapper.updateMenu(dto);
		return dto;
	}

	@Override
	public boolean deleteMenuByPrimaryKey(long id) {
		int i = menuMapper.deleteMenuByPrimaryKey(id);
		return i > 0 ? true : false;
	}
	
	@Override
	public MenuDTO selectMenuByPrimaryKey(long id) {
		return menuMapper.selectMenuByPrimaryKey(id);
	}

	@Override
	public DataTables queryMenuByPage(DataTables dataTables) {
		List<MenuDTO> list = menuMapper.queryDataTablesMenuByPage(dataTables);
		dataTables.setData(list);
		return dataTables;
	}

	@Override
	public List<MenuDTO> queryMenuAll() {
		return menuMapper.queryMenuAll();
	}

	@Override
	public List<MenuDTO> queryHeaderMenuByPermission(long permissionId) {
		List<MenuDTO> list = null;
		String permissionKey = Constants.CURRENT_USER_PERMISSION + permissionId;
		if(redisService.exists(permissionKey)){
			list = (List<MenuDTO>) redisService.get(permissionKey);
		}else{
			list = menuMapper.queryHeaderMenuByPermission(permissionId);
			if(list != null && list.size() > 0){
				redisService.set(permissionKey,list);
			}
		}
 		return list;
	}

	@Override
	public List<MenuDTO> querySafeManagerHeaderMenu() {
		List<MenuDTO> list = null;
		String redisSafeManagerMenuListKey = Constants.SAFE_MANAGER_MENU_LIST;
		if(redisService.exists(redisSafeManagerMenuListKey)){
			list = (List<MenuDTO>) redisService.get(redisSafeManagerMenuListKey);
		}else{
			list = menuMapper.queryHeaderMenuByPermission(Constants.SAFE_MANAGER_MENU_ID);
			if(list != null && list.size() > 0){
				redisService.set(redisSafeManagerMenuListKey,list);
			}
		}
 		return list;
	}
}

